import React from "react";
import {Link, withRouter} from 'react-router-dom'
import bgSrc from "../../../res/images/web/euro/问卷bg@2x.png"
import goBackSrc from "../../../res/images/web/euro/箭头／返回上一页@2x.png"
import {checkAndGoBack} from "../../best-line-up/best-line-up";
import {getEuroQuestionnaire, getEuroQuestionnaireSubmitStatusReq, submitEuroQuestionnaire} from "../../../apis/goApis";
import {log} from "../../../utils/commonfunc";
import LocalStorageService from "../../../utils/LocalStorageService";
import {searchParams} from "../../mall/mall";
import CustomBotton from "../../../shared-components/CustomButton/CustomBotton";
import {Toast} from "antd-mobile";
import submittedSrc from "../../../res/images/web/euro/提交成功@2x.png"

class EuroQuestionnaire extends React.Component {
    constructor(props) {
        super(props)
        this.searchParams = searchParams()
        this.uid = this.searchParams.webview === 'true' ? this.searchParams.uid : LocalStorageService.get('userid')
        this.state = {
            submit: false,
            questions: [],
            text: '',
            top: true,
        }
    }

    componentDidMount() {
        this.getSubmitStatus()
        // this.getQuestions()
        this.bindScrollEvent()
    }

    bindScrollEvent = () => {
        window.addEventListener('scroll', (event) => {
            const ctn = this.ctn
            const top = ctn.getBoundingClientRect().top
            this.setState({
                top: top === 0,
            })
        })
    }

    getSubmitStatus = () => {
        getEuroQuestionnaireSubmitStatusReq({Uid: this.uid})
            .then(res => {
                const data = res.data
                if (data.ok) {
                    const submit = data.res === 1
                    this.setState({
                        submit: submit,
                    }, () => {
                        if (!submit) {
                            this.getQuestions()
                        }
                    })
                }
            })
    }

    getQuestions = () => {
        getEuroQuestionnaire()
            .then(res => {
                const data = res.data
                if (data.ok) {
                    this.setState({
                        questions: data.res.map(question => {
                            log(question)
                            return {
                                ...question,
                                Option: question.Option ? question.Option.map(opt => ({label: opt, checked: false,})) : question.Option,
                            }
                        }),
                    })
                }
            })
    }

    onOptionCheck = (option, optionIndex, questionIndex) => {
        const questions = this.state.questions
        const question = questions[questionIndex]
        const options = question.Option
        const checked = options[optionIndex].checked
        const isMutiCheck = question.Optiontype === 2
        if (!isMutiCheck) {
            questions[questionIndex].Option = options.map(opt => ({...opt, checked: false,}))
        }
        questions[questionIndex].Option[optionIndex].checked = !checked
        this.setState({
            questions: questions,
        })
    }

    onTextareaChange = (e) => {
        this.setState({
            text: e.target.value,
        })
    }

    onSubmit = () => {
        const params = {
            Uid: this.uid,
            Result: this.state.questions.map(question => {
                const result = {
                    Id: question.Id,
                }
                if (Array.isArray(question.Option)) {
                    const array = []
                    question.Option.map((opt, index) => {
                        if (opt.checked) {
                            array.push(index)
                        }
                    })
                    if (array.length === 0) {
                        Toast.fail('有未勾选的选项')
                    }
                    result.Index = array
                } else {
                    result.Txt = this.state.text
                }
                return result
            })
        }
        const allowed = params.Result
            .slice(0, params.Result.length - 1)
            .every(q => q.Index.length > 0)
        if (allowed) {
            submitEuroQuestionnaire(params)
                .then(res => {
                    const data = res.data
                    if (data.ok) {
                        log(data)
                        Toast.success('已提交')
                        this.getSubmitStatus()
                    }
                })
        } else {
            Toast.fail('需要投票完成才能提交')
        }

    }

    render() {
        const list = this.state.questions
        const questionsTemplate = <div>
            {list.map((question, index) => {
                return (
                    <div key={question.Id} className='euro-questionnaire-item'>
                        <p className='euro-questionnaire-item-index'>
                            Q{index + 1}：
                        </p>
                        <div className='flex-1'>
                            <p className='euro-questionnaire-item-title'>
                                {question.Title}？
                            </p>
                            {Array.isArray(question.Option) && question.Option.map((opt, optionIndex) => {
                                return (
                                    <div key={optionIndex} className='euro-questionnaire-item-checkbox'>
                                        <label>
                                            <input type="checkbox" name="type" checked={opt.checked} onChange={() => this.onOptionCheck(opt, optionIndex, index)}/>
                                            <span>{opt.label}</span>
                                        </label>
                                    </div>
                                )
                            })}
                        </div>
                    </div>
                )
            })}
            <div className='euro-questionnaire-item-textarea'>
                <textarea placeholder='欢迎您的参与...' value={this.state.text} onChange={this.onTextareaChange}/>
            </div>
        </div>

        const submittedTemplate = (
            <div className='euro-questionnaire-submitted'>
                <img src={submittedSrc} alt='' className='euro-questionnaire-submitted-image'/>
                <p>提交成功</p>
                <span>请前往APP-“我的”查看奖励</span>
                <button onClick={() => checkAndGoBack(this.props.history, './euro')}>去看比赛</button>
            </div>
        )

        return (
            <div className='euro-questionnaire-container' ref={el => this.ctn = el}>
                <div className='euro-questionnaire-header-wrapper'>
                    <div className={(this.state.submit || !this.state.top) ? 'euro-questionnaire-header euro-questionnaire-header-scroll' : 'euro-questionnaire-header'}>
                        {(!this.state.submit && this.state.top) && <img src={bgSrc} alt='' className='euro-questionnaire-header-bg'/>}
                        <img src={goBackSrc} alt='' className='euro-questionnaire-header-icon' onClick={() => checkAndGoBack(this.props.history, './euro')}/>
                        {(this.state.submit || !this.state.top) && <p className='euro-questionnaire-header-title'>调查问卷</p>}
                    </div>
                </div>

                {this.state.submit && submittedTemplate}
                {!this.state.submit && questionsTemplate}

                {!this.state.submit && <div className='euro-questionnaire-submit'>
                    <button onClick={this.onSubmit}>提交</button>
                </div>}
            </div>
        )
    }
}

export default withRouter(EuroQuestionnaire)